﻿using Barcode_Project.Entity;
using Barcode_Project.Local;
using Barcode_Project.Network;
using DevExpress.Internal;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using log4net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RJCP.IO.Ports;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Numerics;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Net.WebRequestMethods;

namespace Barcode_Project.MatAuxRePrint
{
    public partial class StuffRePrint : DevExpress.XtraEditors.XtraForm
    {
        HttpAgreement http;
        ILog _log;
        Dictionary<string, string> datas;
        DataTable table;

        public StuffRePrint(Dictionary<string, string> pars)
        {
            _log = LogManager.GetLogger(GetType().Name);
            http = new HttpAgreement();
            datas = pars;
            //table = new DataTable();

            InitializeComponent();

            new ComputerTask().LoadPrinter(select_printer);
            new ComputerTask().LoadTemplate(select_template);

        }

        private void StuffRePrint_Load(object sender, EventArgs e)
        {
            table = new DataTable();
            table.Columns.Add("proWeight");
            table.Columns.Add("proMeter");
            gridControl_barInfos.DataSource = table;
        }

        private void lookUp_old_AutoSuggest(object sender, DevExpress.XtraEditors.Controls.LookUpEditAutoSuggestEventArgs e)
        {
            e.QuerySuggestions = new RemoteRequest().BarCodeAutoSuggest(e.Text, e.CancellationToken);
        }

        private void lookUp_old_EditValueChanged(object sender, EventArgs e)
        {
            if (input_old.EditValue != null && input_old.EditValue.ToString().Length >= 12)
            {
                LoadOldData();
            }
        }

        void LoadOldData()
        {
            var codeStr = input_old.EditValue.ToString();

            var barCodeDic = new Dictionary<string, string>();
            barCodeDic["barCode"] = codeStr;

            var returnDic = new Dictionary<string, string>();

            string url = CommonMethods.APIUrl() + "GetOldBarCodeInfo";
            var info = http.HttpPost(url, JsonConvert.SerializeObject(barCodeDic));

            if (string.IsNullOrWhiteSpace(info))
            {
                XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var obj = JsonConvert.DeserializeObject<JObject>(info);
            if (bool.Parse(obj["result"].ToString()))
            {
                returnDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(obj["data"].ToString());
            }

            CommonMethods.SetFormValue(group_data.Controls, returnDic, "input_");

        
        }

        //增行
        private void btn_Add_ItemClick(object sender, ItemClickEventArgs e)
        {
            DataRow dr = table.NewRow();
            table.Rows.Add(dr);
            gridControl_barInfos.DataSource = table;
        }

        //删行
        private void btn_Del_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (table.Rows.Count == 0)
            {
                MessageBox.Show("当前已无数据");
                return;
            }

            int handle = gridView_barInfos.FocusedRowHandle;
            if (handle >= 0)
            {
                //删除
                gridView_barInfos.DeleteRow(handle);
            }



        }

        private void button_rePrint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (!CheckBeforePrint())
            {
                return;
            }

            var json = CollectData();

            string url = CommonMethods.APIUrl() + "MatAuxRePrint";
            var info = http.HttpPost(url, json);

            if (string.IsNullOrWhiteSpace(info))
            {
                XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var obj = JsonConvert.DeserializeObject<JObject>(info);

            if (bool.Parse(obj["result"].ToString()))
            {
                //var table = CommonMethods.CreatePrintTableByDictionary(datas, obj["data"].ToString());
                var bars= obj["data"].ToString().Split(',');
                foreach (var b in bars)
                {
                    var printTable = new RemoteRequest().GetReBarInfo(b);
                    printTable.Rows[0]["barCode"] = b;

                    var printerName = ((ItemSelector)select_printer.GetSelectedDataRow()).code;
                    var templatePath = ((ItemSelector)select_template.GetSelectedDataRow()).code;//模板路径

                    new ComputerTask().StartPrintingTask(printTable, printerName, templatePath);

                }

                input_old.EditValue = "";
                table = new DataTable();
                table.Columns.Add("proWeight");
                table.Columns.Add("proMeter");
                gridControl_barInfos.DataSource = table;
            }
            else
            {
                XtraMessageBox.Show(obj["message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

        }

        // 打印之前，检查必填项
        bool CheckBeforePrint()
        {
            var result = false;

            if (input_old.EditValue == null)
            {
                XtraMessageBox.Show("请填写条码");
                return result;
            }

            if (string.IsNullOrEmpty(input_old.EditValue.ToString()))
            {
                XtraMessageBox.Show("请填写条码");
                return result;
            }

            #region 条码总数量不能大于原码数量
            var totalWeight = 0m;
            var totalMeter = 0m;
            foreach (DataRow dr in table.Rows)
            {
                if(string.IsNullOrEmpty(dr["proWeight"].ToString()) || string.IsNullOrEmpty(dr["proMeter"].ToString()))
                {
                    continue;
                }
                if (!decimal.TryParse(dr["proWeight"].ToString(), out decimal w))
                {
                    MessageBox.Show("请检查填写重量"); return result;
                }
                if (!decimal.TryParse(dr["proMeter"].ToString(), out decimal m))
                {
                    MessageBox.Show("请检查填写数量"); return result;
                }
                totalWeight += decimal.Parse(dr["proWeight"].ToString());
                totalMeter += decimal.Parse(dr["proMeter"].ToString());
            }

            if(totalWeight> decimal.Parse(input_proWeight.Text.ToString()))
            {
                XtraMessageBox.Show("打印条码总重量："+ totalWeight +"大于原条码重量："+ input_proWeight.Text.ToString());
                return result;
            }

            if (totalMeter > decimal.Parse(input_proMeter.Text.ToString()))
            {
                XtraMessageBox.Show("打印条码总数量：" + totalMeter + "大于原条码数量：" + input_proMeter.Text.ToString());
                return result;
            }

            #endregion

            if (select_printer.GetSelectedDataRow() == null)
            {
                XtraMessageBox.Show("请选择打印机");
                return result;
            }
            if (select_template.GetSelectedDataRow() == null)
            {
                XtraMessageBox.Show("请选择打印模板");
                return result;
            }

            result = true;
            return result;
        }

        // 组织数据
        string CollectData()
        {
            datas["oldBarCode"] = input_old.EditValue.ToString();

            List<Dictionary<string,string>> list = new List<Dictionary<string, string>>();
            foreach (DataRow dr in table.Rows)
            {
                if (string.IsNullOrEmpty(dr["proWeight"].ToString()) || string.IsNullOrEmpty(dr["proMeter"].ToString()))
                {
                    continue;
                }
                var dic = new Dictionary<string, string>();
                dic["proWeight"] = dr["proWeight"].ToString();
                dic["proMeter"] = dr["proMeter"].ToString();
                list.Add(dic);
            }
            datas["barDatas"] = JsonConvert.SerializeObject(list);

            return JsonConvert.SerializeObject(datas);
        }

        private void button_exit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Application.Exit();
        }

        private void btn_update_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var r = XtraMessageBox.Show("即将关闭程序进行升级，是否继续？", "提示", MessageBoxButtons.OKCancel);
            if (r == DialogResult.OK)
            {
                new RemoteRequest().UpdateCmdProgram();
            }
        }

      
    }
}